package com.hucc.redislock.command;

import com.hucc.redislock.RedisLockContext;
import com.hucc.redislock.result.CommandResult;

import java.util.ArrayList;
import java.util.List;

/**
 * 删除锁 redis命令
 */
public class DelLockRedisCommand extends AbstractRedisCommand {
    public DelLockRedisCommand(String lockName, String threadName) {
        super(lockName, threadName);
    }

    @Override
    public CommandResult execute() {

        String script =
                "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
                    "return nil;" +
                "end; " +
                "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
                "if (counter > 0) then " +
                    "redis.call('pexpire', KEYS[1], ARGV[2]); " +
                    "return 0; " +
                "else " +
                    "redis.call('del', KEYS[1]); " +
                    "redis.call('publish', KEYS[2], ARGV[1]); " +
                    "return 1; "+
                "end; " +
                "return nil;";

        List<String> keys = new ArrayList<String>();
        keys.add(lockName);
        keys.add(getChannelName(lockName));

        List<String> args = new ArrayList<String>();
        args.add("1");
        args.add(String.valueOf(RedisLockContext.getRedisLockConfig().getLockWatchdogTimeout()));
        args.add(threadName);

        Long evalResult = (Long) executeScript(script, keys, args);
        CommandResult commandResult = new CommandResult();
        if (evalResult == null) {
            commandResult.setSuccess(false);
            commandResult.setErrorMessage(String.format("当前线程[%s]没有拥有该锁!", threadName));
        } else {
            commandResult.setSuccess(true);
            commandResult.setCode(evalResult.intValue());
        }

        return commandResult;
    }
}
